# cython: language_level=3
import os
from datetime import datetime

from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.db.sql.intra_day_task import (
    save_intra_day_task,
    save_intra_day_task_resource,
)
from app.middlewares.redis import get_redis
from app.models import IntraDayTaskResource
from app.models.intra_day_task import IntraDayTask
from app.schemas.platform import GetIntraDayTaskRequest
from common.database import get_db
from common.http import ok_response, error_response
from common.redis import MyRedis
from common.time import get_date_today

router = APIRouter(tags=["platform-intra-task"])
router.prefix = "/v2"
load_dotenv()
CREDIT_CODE = os.getenv("CREDIT_CODE")


@router.post("/getIntraDayTask")
def get_intra_day_task(
        payload: GetIntraDayTaskRequest,
        db: Session = Depends(get_db),
        redis: MyRedis = Depends(get_redis),
):
    """
    2.7
    虚拟电厂平台向负荷聚合平台下发日内紧急调控任务
    """
    if payload.creditCode != CREDIT_CODE:
        return error_response(5000, "creditCode不正确")

    intra_day_task = IntraDayTask()
    intra_day_task.task_code = payload.taskCode
    intra_day_task.task_name = payload.taskName
    save_intra_day_task(db, None, intra_day_task)
    intra_day_task_resources: list[IntraDayTaskResource] = []

    for resource in payload.resourceList:
        temp = IntraDayTaskResource(
            start_time=datetime.strptime(resource.startTime, "%Y-%m-%d %H:%M:%S"),
            end_time=datetime.strptime(resource.endTime, "%Y-%m-%d %H:%M:%S"),
            target_power=resource.targetPower,
            task_code=payload.taskCode,
            resource_id=resource.resourceId,
            execution_date=get_date_today(),
            handle_status=0,
        )
        intra_day_task_resources.append(temp)

    save_intra_day_task_resource(db, intra_day_task_resources)
    ret_resource_list = []
    for resource in payload.resourceList:
        # update_resource_rtd(resource.resourceId, dict(resource), redis)
        send_payload = {
            "resourceId": resource.resourceId,
            "targetPower": resource.targetPower,
            "startTime": resource.startTime,
            "endTime": resource.endTime,
        }
        # send2resource(db, resource.resourceId, send_payload)
        ret_resource_list.append(send_payload)

    ret = {
        "confirmResult": "Y",  # Y表示同意，N表示拒绝
        "page": payload.page,
        "totalPage": payload.totalPage,
        "resourceList": ret_resource_list,
    }
    return ok_response([ret])
